package netty.proto;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import student.DateType;
import student.Message;
import student.Student;
import student.Worker;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {


    /**
     * 读取数据
     * @param ctx: 上下文对象，其中包含 pipeline、channel...
     * @param msg: 客户端发送数据
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("接收到数据: " + msg);
        Message message = (Message) msg;
        switch (message.getType()) {
            case StudentType -> {
                Student student = message.getStudent();
                System.out.println("student: " + student);
            }
            case WorkerType -> {
                Worker worker = message.getWorker();
                System.out.println("worker: " + worker);
            }
        }
    }

    /**
     * 读取数据完毕
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        // 发送一个 student 对象
//        Message studentMessage = Message.newBuilder()
//                .setStudent(Student.newBuilder().setId(1).setName("哈哈"))
//                .setType(DateType.StudentType)
//                .build();
//        // 写入消息并刷新缓存
//        ctx.writeAndFlush(studentMessage);
//        System.out.println("服务器回复消息");
    }

    /**
     * 处理异常, 并关闭通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }
}
